package cn.com.sbell.vss.csg.vsclient.hikvision;

import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import cn.com.sbell.vss.csg.vap.bean.AlarmMessage;
import cn.com.sbell.vss.csg.vsclient.AccessInfo;
import cn.com.sbell.vss.csg.vsclient.hikvision.bean.DeviceCfg;
import cn.com.sbell.vss.csg.vsclient.hikvision.bean.DeviceInfo;
import cn.com.sbell.vss.csg.vsclient.hikvision.bean.FtpUpgradeCFG;
import cn.com.sbell.vss.csg.vsclient.util.AlarmDispatchGroup;

public class VsUpgradeThread extends Thread {
	private String fileURL;
	private int timeout;
	private AccessInfo accessInfo;
	private String deviceId;
	private final static Log logger = LogFactory.getLog(VsUpgradeThread.class);
	
	public VsUpgradeThread(String fileURL, int timeout, AccessInfo accessInfo, String deviceId) {
		this.fileURL = fileURL;
		this.timeout = timeout;
		this.accessInfo = accessInfo;
		this.deviceId = deviceId;
	}

	public void run() {
		super.run();
		int upgradeStatus=0; 
		int upgrade=0;					
//		File updateFile = null;
//		String fullUpdateFileName = null;

		String beforeUpgradeVersion = ""; 
		DeviceInfo deviceInfo=new DeviceInfo();
	
		int vsLoginuserId=HcNetAdapter.login(accessInfo.getVsIp(),accessInfo.getVsPort().intValue(),
				accessInfo.getVsLoginUsername(),accessInfo.getVsLoginPassword(),
				deviceInfo);
		
		if(vsLoginuserId==-1){
			return;
		}
		
		DeviceCfg deviceCfg=new DeviceCfg();
		HcNetAdapter.getDeviceCfg(vsLoginuserId,0,deviceCfg);
		beforeUpgradeVersion = deviceCfg.getFullSoftwareVersion();
		
//		try {
//			updateFile = getUpdateFileName();
//			fullUpdateFileName = updateFile.getCanonicalPath();
//		} catch (MalformedURLException e1) {
//			reportAlarm("VS_UPGRADE",accessInfo.getUserId()+","
//					+beforeUpgradeVersion+","+beforeUpgradeVersion+","+"3"
//					,vsLoginuserId,accessInfo.getVsIp(),deviceId);
//			return;
//		} catch (IOException e1) {
//			reportAlarm("VS_UPGRADE",accessInfo.getUserId()+","
//					+beforeUpgradeVersion+","+beforeUpgradeVersion+","+"3"
//					,vsLoginuserId,accessInfo.getVsIp(),deviceId);
//			return;
//		}
		FtpUpgradeCFG upgradeCFG=null;
		try {
			upgradeCFG = parseURL();
		} catch (Exception e1) {
			logger.debug("occuered error :"+e1);
			reportAlarm("VS_UPGRADE",accessInfo.getUserId()+","
					+beforeUpgradeVersion+","+beforeUpgradeVersion+","+"3"
					,vsLoginuserId,accessInfo.getVsIp(),deviceId);
			return;
		}		
		upgrade=HcNetAdapter.upgrade(vsLoginuserId,upgradeCFG);
		if(upgrade<0){
			logger.debug("function HcNetAdapter.upgrade() error ,status is ["+upgrade+"]");
			reportAlarm("VS_UPGRADE",accessInfo.getUserId()+","
					+beforeUpgradeVersion+","+beforeUpgradeVersion+","+"3"
					,vsLoginuserId,accessInfo.getVsIp(),deviceId);
			return;
		}
		
		int i=0;
		for(;i<timeout*60;i++){
			upgradeStatus=HcNetAdapter.getUpgradeState(upgrade);
			if(upgradeStatus!=2){				
				break;
			}
//			if(upgradeStatus==-1){				
//				break;
//			}
//			if(upgradeStatus==5){
//				break;
//			}
			try {
				sleep(1000);
			} catch (InterruptedException e) {
				//Ignore
			}
		}
		logger.debug("upgrade status:"+upgradeStatus);
		switch(upgradeStatus){
			case 1:				
				HcNetAdapter.reboot(vsLoginuserId);
				int secondvsLoginuserId=-1;
				for(int j=0;j<timeout*60-i;j++){
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						//Ignore
					}
					secondvsLoginuserId=HcNetAdapter.login(accessInfo.getVsIp(),accessInfo.getVsPort().intValue(),
							accessInfo.getVsLoginUsername(),accessInfo.getVsLoginPassword(),
							deviceInfo);					
					if(secondvsLoginuserId<0){						
						continue;
					}else{
						break;
					}
					
				
				}
				if(secondvsLoginuserId<0){
					reportAlarm(upgrade,"VS_UPGRADE",accessInfo.getUserId()+","+
							beforeUpgradeVersion+","+beforeUpgradeVersion+","
							+"4",accessInfo.getVsIp(),deviceId);
					return;
				}
				DeviceCfg device=new DeviceCfg();
				HcNetAdapter.getDeviceCfg(secondvsLoginuserId,0,device);	
				String currentVersion =  device.getFullSoftwareVersion();
				reportAlarm("VS_UPGRADE",accessInfo.getUserId()+","+
						beforeUpgradeVersion+","+ currentVersion+","
						+"0",upgrade,secondvsLoginuserId,accessInfo.getVsIp(),deviceId);
				
										
				break;
			case -1:
				reportAlarm("VS_UPGRADE",accessInfo.getUserId()+","
						+beforeUpgradeVersion+","+beforeUpgradeVersion+","+"4",upgrade,vsLoginuserId
						,accessInfo.getVsIp(),deviceId);
				break;
			case  5:
				reportAlarm("VS_UPGRADE",accessInfo.getUserId()+","
						+beforeUpgradeVersion+","+beforeUpgradeVersion+","+"2",upgrade,vsLoginuserId,
						accessInfo.getVsIp(),deviceId);
				break;
			default:
				reportAlarm("VS_UPGRADE",accessInfo.getUserId()+","
						+beforeUpgradeVersion+","+beforeUpgradeVersion+","+"1",upgrade,vsLoginuserId,
						accessInfo.getVsIp(),deviceId);
				break;
			
		}
		
//		updateFile.delete();
	}

	private void reportAlarm(String alarmType, String data, int upgrade,
			int userid, String vsIP, String deviceId) {
		AlarmMessage message = new AlarmMessage();
		message.setAlarmType(alarmType);
		message.setData(data);
		message.setServerIp(vsIP);
		message.setServerType("VS");
		message.setDeviceId(deviceId);
		message.setAlarmCode(AlarmMessage.ALARMCODE_VSUPGRADE);
		message.setEventType(AlarmMessage.EVENTTYPE_DEVICEALARM);
		AlarmDispatchGroup.getAlarmDispatchGroup().addMessage(message);
		HcNetAdapter.closeUpgradeHandle(upgrade);		
		HcNetAdapter.logout(userid);

	}

	private void reportAlarm(String alarmType, String data, int userid,
			String vsIP, String deviceId) {
		AlarmMessage message = new AlarmMessage();
		message.setAlarmType(alarmType);
		message.setData(data);
		message.setServerIp(vsIP);
		message.setServerType("VS");
		message.setDeviceId(deviceId);
		message.setAlarmCode(AlarmMessage.ALARMCODE_VSUPGRADE);
		message.setEventType(AlarmMessage.EVENTTYPE_DEVICEALARM);
		AlarmDispatchGroup.getAlarmDispatchGroup().addMessage(message);
		HcNetAdapter.logout(userid);

	}
	private void reportAlarm( int upgrade,String alarmType, String data,
			String vsIP, String deviceId) {
		AlarmMessage message = new AlarmMessage();
		message.setAlarmType(alarmType);
		message.setData(data);
		message.setServerIp(vsIP);
		message.setServerType("VS");
		message.setDeviceId(deviceId);
		message.setAlarmCode(AlarmMessage.ALARMCODE_VSUPGRADE);
		message.setEventType(AlarmMessage.EVENTTYPE_DEVICEALARM);
		AlarmDispatchGroup.getAlarmDispatchGroup().addMessage(message);	
		HcNetAdapter.closeUpgradeHandle(upgrade);	
	}

//	private File getUpdateFileName() throws IOException{
//	
//		String serverupdatefilename = "update." + System.currentTimeMillis() + ".tmp";
//		File file = new File(serverupdatefilename);
//		URL url = new URL(fileURL);
//		InputStream input = url.openConnection().getInputStream();
//		FileOutputStream output = new FileOutputStream(file);
//		byte[] buffer = new byte[1024];
//
//		int count = input.read(buffer);
//		while (count > 0) {
//			output.write(buffer, 0, count);
//			count = input.read(buffer);
//		}
//		
//		output.flush();
//		input.close();
//		output.close();
//		return file;
//	}
	private FtpUpgradeCFG parseURL() throws MalformedURLException{
		FtpUpgradeCFG upgradeCFG=new FtpUpgradeCFG();		
		URL url=new URL(fileURL);
		upgradeCFG.ftpIp=url.getHost();
		upgradeCFG.ftpPort=url.getPort();
		String[] userInfo=url.getUserInfo().split(":");	 
		
		try {
			upgradeCFG.username=userInfo[0].getBytes(HikVisionDVRClient.CHARSET);
			upgradeCFG.password=userInfo[1].getBytes(HikVisionDVRClient.CHARSET);
		} catch (UnsupportedEncodingException e) {
			logger.debug("occur Exception "+e);
		}
		
		
		logger.debug("ftpIP="+upgradeCFG.ftpIp+";ftpPort="+upgradeCFG.ftpPort+"\n");
		logger.debug("userInfo is:"+userInfo[0]+":"+userInfo[1]+"\n");
		
		String fileFullPath=url.getPath();
		logger.debug("fileFullPath is :"+fileFullPath);
		int lastindex=fileFullPath.lastIndexOf("/");
		
		String fileName=fileFullPath.substring(lastindex+1);
		logger.debug("fileName is :"+fileName);
		try {
			upgradeCFG.fileName=fileName.getBytes(HikVisionDVRClient.CHARSET);
		} catch (UnsupportedEncodingException e) {
			logger.debug("occur Exception "+e);
		}
		
		String filePath=fileFullPath.substring(0,lastindex);
//		if(filePath.equalsIgnoreCase(""))
//		{
//			filePath="/";
//		}
		logger.debug("filePath is : ["+filePath +" ]");
		try {
			upgradeCFG.path=filePath.getBytes(HikVisionDVRClient.CHARSET);
		} catch (UnsupportedEncodingException e) {
			logger.debug("occur Exception "+e);
		}		
		return upgradeCFG;
	}

}
